using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 写书流程配置服务实现
    /// </summary>
    public class WritingWorkflowConfigService : IWritingWorkflowConfigService
    {
        private readonly IDataStorageService _dataStorage;
        private readonly ILogger<WritingWorkflowConfigService> _logger;
        private WritingWorkflowConfig? _currentAppliedConfig;

        public WritingWorkflowConfigService(IDataStorageService dataStorage, ILogger<WritingWorkflowConfigService> logger)
        {
            _dataStorage = dataStorage;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有流程配置
        /// </summary>
        public async Task<List<WritingWorkflowConfig>> GetAllConfigsAsync()
        {
            try
            {
                var configs = await _dataStorage.GetWritingWorkflowConfigsAsync();
                return configs.OrderByDescending(c => c.IsDefault)
                    .ThenByDescending(c => c.UpdatedAt)
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有写书流程配置失败");
                throw;
            }
        }

        /// <summary>
        /// 根据ID获取流程配置
        /// </summary>
        public async Task<WritingWorkflowConfig?> GetConfigByIdAsync(int id)
        {
            try
            {
                return await _dataStorage.GetWritingWorkflowConfigAsync(id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取写书流程配置失败，ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 获取默认流程配置
        /// </summary>
        public async Task<WritingWorkflowConfig> GetDefaultConfigAsync()
        {
            try
            {
                var configs = await _dataStorage.GetWritingWorkflowConfigsAsync();
                var defaultConfig = configs.FirstOrDefault(c => c.IsDefault);

                if (defaultConfig == null)
                {
                    defaultConfig = await CreateDefaultConfigAsync();
                }

                return defaultConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取默认写书流程配置失败");
                throw;
            }
        }

        /// <summary>
        /// 保存流程配置
        /// </summary>
        public async Task<WritingWorkflowConfig> SaveConfigAsync(WritingWorkflowConfig config)
        {
            try
            {
                var savedConfig = await _dataStorage.CreateWritingWorkflowConfigAsync(config);
                _logger.LogInformation($"保存写书流程配置成功，ID: {savedConfig.Id}, 名称: {savedConfig.Name}");
                return savedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存写书流程配置失败，名称: {config.Name}");
                throw;
            }
        }

        /// <summary>
        /// 更新流程配置
        /// </summary>
        public async Task<WritingWorkflowConfig> UpdateConfigAsync(WritingWorkflowConfig config)
        {
            try
            {
                var updatedConfig = await _dataStorage.UpdateWritingWorkflowConfigAsync(config);
                _logger.LogInformation($"更新写书流程配置成功，ID: {updatedConfig.Id}, 名称: {updatedConfig.Name}");
                return updatedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新写书流程配置失败，ID: {config.Id}");
                throw;
            }
        }

        /// <summary>
        /// 删除流程配置
        /// </summary>
        public async Task<bool> DeleteConfigAsync(int id)
        {
            try
            {
                var config = await _dataStorage.GetWritingWorkflowConfigAsync(id);
                if (config == null)
                {
                    return false;
                }

                if (config.IsDefault)
                {
                    throw new InvalidOperationException("不能删除默认配置");
                }

                await _dataStorage.DeleteWritingWorkflowConfigAsync(id);
                _logger.LogInformation($"删除写书流程配置成功，ID: {id}, 名称: {config.Name}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除写书流程配置失败，ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 设置默认配置
        /// </summary>
        public async Task<bool> SetDefaultConfigAsync(int id)
        {
            try
            {
                var allConfigs = await _dataStorage.GetWritingWorkflowConfigsAsync();
                foreach (var config in allConfigs)
                {
                    config.IsDefault = false;
                    await _dataStorage.UpdateWritingWorkflowConfigAsync(config);
                }

                var targetConfig = allConfigs.FirstOrDefault(c => c.Id == id);
                if (targetConfig != null)
                {
                    targetConfig.IsDefault = true;
                    await _dataStorage.UpdateWritingWorkflowConfigAsync(targetConfig);

                    _logger.LogInformation($"设置默认写书流程配置成功，ID: {id}, 名称: {targetConfig.Name}");
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"设置默认写书流程配置失败，ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 创建默认配置
        /// </summary>
        public async Task<WritingWorkflowConfig> CreateDefaultConfigAsync()
        {
            try
            {
                var defaultConfig = new WritingWorkflowConfig
                {
                    Name = "默认配置",
                    Description = "系统默认的写书流程配置，包含完整的写书步骤",
                    IsDefault = true,
                    // 启用所有基础功能
                    EnableOverallOutlineGeneration = true,
                    EnableWorldSettingGeneration = true,
                    EnableVolumeOutlineGeneration = true,
                    EnableChapterOutlineGeneration = true,
                    EnableChapterContentGeneration = true,
                    EnableTimelineUpdate = true,
                    EnableSequentialMode = true,
                    EnableBatchMode = false,
                    // 新增步骤管理设定
                    EnableCustomStepOrder = false,
                    AllowStepSkipping = true,
                    ExecutionMode = StepExecutionMode.Sequential,
                    CustomSteps = CreateDefaultSteps()
                };

                var savedConfig = await _dataStorage.CreateWritingWorkflowConfigAsync(defaultConfig);
                _logger.LogInformation($"创建默认写书流程配置成功，ID: {savedConfig.Id}");
                return savedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建默认写书流程配置失败");
                throw;
            }
        }

        /// <summary>
        /// 创建默认步骤列表
        /// </summary>
        private List<WorkflowStep> CreateDefaultSteps()
        {
            return new List<WorkflowStep>
            {
                new()
                {
                    Id = "world_setting",
                    Name = "生成世界设定",
                    Description = "生成详细的世界观设定，为整个小说世界建立基础框架",
                    Order = 1,
                    IsEnabled = true,
                    IsRequired = false,
                    CanSkip = true,
                    EstimatedDurationMinutes = 10,
                    Dependencies = new List<string>()
                },
                new()
                {
                    Id = "overall_outline",
                    Name = "生成全书大纲",
                    Description = "基于世界设定制定整体故事框架和主要情节发展",
                    Order = 2,
                    IsEnabled = true,
                    IsRequired = true,
                    CanSkip = false,
                    EstimatedDurationMinutes = 15,
                    Dependencies = new List<string> { "world_setting" }
                },
                new()
                {
                    Id = "volume_outlines",
                    Name = "生成卷宗大纲",
                    Description = "将全书大纲细化为各卷的具体规划",
                    Order = 3,
                    IsEnabled = true,
                    IsRequired = true,
                    CanSkip = false,
                    EstimatedDurationMinutes = 20,
                    Dependencies = new List<string> { "overall_outline" }
                },
                new()
                {
                    Id = "chapter_outlines",
                    Name = "生成章节细纲",
                    Description = "为每个章节生成详细的创作细纲",
                    Order = 4,
                    IsEnabled = true,
                    IsRequired = false,
                    CanSkip = true,
                    EstimatedDurationMinutes = 30,
                    Dependencies = new List<string> { "volume_outlines" }
                },
                new()
                {
                    Id = "chapter_content",
                    Name = "生成章节正文",
                    Description = "基于细纲生成章节正文内容，由具体写书功能调用",
                    Order = 5,
                    IsEnabled = true,
                    IsRequired = true,
                    CanSkip = false,
                    EstimatedDurationMinutes = 60,
                    Dependencies = new List<string> { "chapter_outlines" },
                    // 标记为配置项，不直接执行导出
                    IsConfigurationOnly = true
                },
                new()
                {
                    Id = "timeline_update",
                    Name = "更新时间线",
                    Description = "每章生成后更新时间线，确保故事连贯性",
                    Order = 6,
                    IsEnabled = true,
                    IsRequired = false,
                    CanSkip = true,
                    EstimatedDurationMinutes = 5,
                    Dependencies = new List<string> { "chapter_content" }
                }
            };
        }

        /// <summary>
        /// 导出配置到文件
        /// </summary>
        public async Task<bool> ExportConfigAsync(int id, string filePath)
        {
            try
            {
                var config = await GetConfigByIdAsync(id);
                if (config == null)
                {
                    return false;
                }

                var json = JsonConvert.SerializeObject(config, Formatting.Indented);
                await File.WriteAllTextAsync(filePath, json);

                _logger.LogInformation($"导出写书流程配置成功，ID: {id}, 文件: {filePath}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"导出写书流程配置失败，ID: {id}, 文件: {filePath}");
                throw;
            }
        }

        /// <summary>
        /// 从文件导入配置
        /// </summary>
        public async Task<WritingWorkflowConfig?> ImportConfigAsync(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    return null;
                }

                var json = await File.ReadAllTextAsync(filePath);
                var config = JsonConvert.DeserializeObject<WritingWorkflowConfig>(json);

                if (config == null)
                {
                    return null;
                }

                config.Id = 0;
                config.IsDefault = false;
                config.CreatedAt = DateTime.Now;
                config.UpdatedAt = DateTime.Now;
                config.Name = $"{config.Name}_导入";

                var savedConfig = await SaveConfigAsync(config);
                _logger.LogInformation($"导入写书流程配置成功，文件: {filePath}, 新ID: {savedConfig.Id}");
                return savedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"导入写书流程配置失败，文件: {filePath}");
                throw;
            }
        }

        /// <summary>
        /// 验证配置的完整性
        /// </summary>
        public async Task<bool> ValidateConfigAsync(WritingWorkflowConfig config)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(config.Name))
                {
                    return false;
                }

                if (config.OverallOutlineMaxTokens <= 0 || config.OverallOutlineMaxTokens > 100000)
                {
                    return false;
                }

                if (config.OverallOutlineTemperature < 0 || config.OverallOutlineTemperature > 2)
                {
                    return false;
                }

                if (config.RetryCount < 0 || config.RetryCount > 10)
                {
                    return false;
                }

                if (config.GenerationInterval < 0 || config.GenerationInterval > 60000)
                {
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证写书流程配置失败");
                return false;
            }
        }

        /// <summary>
        /// 获取配置的预览信息
        /// </summary>
        public async Task<string> GetConfigPreviewAsync(int id)
        {
            try
            {
                var config = await GetConfigByIdAsync(id);
                if (config == null)
                {
                    return "配置不存在";
                }

                return $@"配置名称：{config.Name}
配置描述：{config.Description}
是否默认：{(config.IsDefault ? "是" : "否")}
创建时间：{config.CreatedAt:yyyy-MM-dd HH:mm:ss}
更新时间：{config.UpdatedAt:yyyy-MM-dd HH:mm:ss}

启用的步骤：
- 全书大纲生成：{(config.EnableOverallOutlineGeneration ? "是" : "否")}
- 世界设定生成：{(config.EnableWorldSettingGeneration ? "是" : "否")}
- 卷宗大纲生成：{(config.EnableVolumeOutlineGeneration ? "是" : "否")}
- 章节细纲生成：{(config.EnableChapterOutlineGeneration ? "是" : "否")}
- 章节正文生成：{(config.EnableChapterContentGeneration ? "是" : "否")}
- 时间线更新：{(config.EnableTimelineUpdate ? "是" : "否")}

生成模式：{(config.EnableSequentialMode ? "顺序生成" : "批量生成")}
重试次数：{config.RetryCount}
生成间隔：{config.GenerationInterval}ms
输出格式：{config.OutputFileFormat}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取写书流程配置预览失败，ID: {id}");
                return "获取预览失败";
            }
        }

        /// <summary>
        /// 应用配置到分步写书服务
        /// </summary>
        public async Task<bool> ApplyConfigToServiceAsync(int configId)
        {
            try
            {
                var config = await GetConfigByIdAsync(configId);
                if (config == null)
                {
                    return false;
                }

                _currentAppliedConfig = config;
                _logger.LogInformation($"应用写书流程配置成功，ID: {configId}, 名称: {config.Name}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"应用写书流程配置失败，ID: {configId}");
                throw;
            }
        }

        /// <summary>
        /// 获取当前应用的配置
        /// </summary>
        public async Task<WritingWorkflowConfig?> GetCurrentAppliedConfigAsync()
        {
            try
            {
                if (_currentAppliedConfig == null)
                {
                    _currentAppliedConfig = await GetDefaultConfigAsync();
                }

                return _currentAppliedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取当前应用的写书流程配置失败");
                throw;
            }
        }
    }
}
